package com.aoyy.dao;

import java.util.List;
import org.springframework.stereotype.Repository;
import com.aoyy.model.Topic;
import com.aoyy.util.Page;
import com.aoyy.constant.Constants;
/**===============================================================================================================================================
 * DAO class <code>TopicDao</code> is to query topics by <code>boardId</code>
 * @author this author
 * @date 2017-08-06
 * =============================================================================================================================================== */
@Repository
public class TopicDao extends BaseDao<Topic> {
	// Query topics by boardId
	public List<Topic> queryTopicsByBoardId(Integer boardId) {
		String hql = "from Topic where board.boardId = " + boardId + " order by createTime desc";
		@SuppressWarnings("unchecked")
		List<Topic> list = this.find(hql);
		return list;
	}
	
	// Paged Query topics by boardId
	public Page pagedQuery(Integer pageNo, Integer pageSize, Integer boardId) {
		String hql = "from Topic where board.boardId = " + boardId + " order by createTime desc";
		return this.pagedQuery(hql, pageNo, pageSize);
	}
	
	// Query topic by topicId
	public Topic queryTopicByTopicId(Integer topicId) {
		String hql = "from Topic where topicId = " + topicId;
		@SuppressWarnings("rawtypes")
		List list = this.find(hql);
		if (list != null && !list.isEmpty()) {
			return (Topic) list.get(0);
		}
		return null;
	}
	
	// Update topic digest by topicId and checked, here checked is the original value of digest.  
	public void updateTopicDigest(Integer topicId, Integer checked) {
		if (checked == Constants.DIGEST_NO) {
			String hql = "update Topic set digest = " + Constants.DIGEST_YES + " where topicId = " + topicId;
			this.executeUpdate(hql);
		} else if (checked == Constants.DIGEST_YES){
			String hql = "update Topic set digest = " + Constants.DIGEST_NO + " where topicId = " + topicId;
			this.executeUpdate(hql);
		}
	}
	
	// Update views of topic by topicId
	public void updateTopicViewsByTopicId(Integer topicId) {
		String hql = "update Topic set views = views + 1 where topicId = " + topicId;
		this.executeUpdate(hql);
	}
	
}
